package com.song.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.song.entity.BorrowInfo;
import com.song.entity.Borrower;
import com.song.entity.IntegralGrade;
import com.song.entity.UserInfo;
import com.song.entity.vo.BorrowInfoApprovalVO;
import com.song.entity.vo.BorrowerDetailVO;
import com.song.enums.BorrowInfoStatusEnum;
import com.song.enums.BorrowStatusEnum;
import com.song.mapper.BorrowInfoMapper;
import com.song.mapper.BorrowerMapper;
import com.song.mapper.IntegralGradeMapper;
import com.song.mapper.UserInfoMapper;
import com.song.service.BorrowInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.song.service.BorrowerService;
import com.song.service.DictService;
import com.song.service.LendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Song
 * @since 2025-01-03
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {


    @Autowired
    private UserInfoMapper userInfoMapper;

    //积分等级mapper
    @Autowired
    private IntegralGradeMapper integralGradeMapper;

    @Autowired
    private DictService dictService;

    @Autowired
    private BorrowerMapper borrowerMapper;

    @Autowired
    private BorrowerService borrowerService;
    @Autowired
    private LendService lendService;


    @Override
    public BigDecimal getBorrowAmount(Long userId) {

        //获取用户的积分
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //判断用户不为空也是必要的
        Integer integral = userInfo.getIntegral();

        //根据积分获取借款额度
        QueryWrapper<IntegralGrade> wrapper = new QueryWrapper<>();
        wrapper.le("integral_start",integral);
        wrapper.ge("integral_end",integral);
         //拿到积分等级对象
        IntegralGrade integralGrade = integralGradeMapper.selectOne(wrapper);
        //判断为空
        if(integralGrade==null){
              return  new BigDecimal("0");
        }


        return integralGrade.getBorrowAmount();
    }

    @Override
    public Integer getBorrowInfoStatus(Long userId) {
        QueryWrapper<BorrowInfo> wrapper = new QueryWrapper<>();
        wrapper.select("status").eq("user_id",userId);

        List<Object> objects = baseMapper.selectObjs(wrapper);
        if(objects.size()==0){
               return BorrowStatusEnum.NO_BORROW.getStatus();
        }

       Integer status= (Integer) objects.get(0);

        return status;
    }

    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo, Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);

        //判断用户绑定状态是否绑定了 必须绑定才行

        // 判断用户信息的认证状态 必须是审批通过才行

        //判断借款额度问题 ??    能借 10w 借15W
        //根据userId  获取借款额度
        BigDecimal borrowAmount = this.getBorrowAmount(userId);
        //判断一下
        if(borrowInfo.getAmount().doubleValue()>borrowAmount.doubleValue()){
          //不  可以借钱
        }

        //可以借钱
        borrowInfo.setUserId(userId);//借钱人
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));
        borrowInfo.setStatus(BorrowInfoStatusEnum.BORROW_OK.getStatus());

        baseMapper.insert(borrowInfo);

    }

    /**
     * 查询借款信息发方法
     * @return
     */
    @Override
    public List<BorrowInfo> selectList() {
        //自定义方法查询所有借款信息
        List<BorrowInfo> borrowInfoList = baseMapper.selectBorrowInfoList();
        //遍历所有借款信息
        borrowInfoList.forEach(borrowInfo -> {
            //因为借款信息中的数据不足以显示全部页面信息,所以需要在遍历的时候插入其他的信息
            String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod",borrowInfo.getReturnMethod());//还款方式
            String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse",borrowInfo.getMoneyUse());//资金用途
            String msgStatus = BorrowInfoStatusEnum.getMsgStatus(borrowInfo.getStatus());//借款状态
            //其他数据放到map里
            borrowInfo.getParam().put("returnMethod",returnMethod);
            borrowInfo.getParam().put("moneyUse",moneyUse);
            borrowInfo.getParam().put("status",msgStatus);
        });
        return borrowInfoList;
    }

    //借款列表
    @Override
    public Map<String, Object> getBorrowInfoAndBorrowById(Long id) {
        /**
         * 1.借款信息
         * 2.借款人信息
         */

        //1.
        //根据借款信息id查询借款信息
        BorrowInfo borrowInfo = baseMapper.selectById(id);
        //借款信息中的属性不足以显示页面全部信息，需要进行扩展
        String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());//还款方式
        String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());//资金用途
        String msgStatus = BorrowInfoStatusEnum.getMsgStatus(borrowInfo.getStatus());//借款的状态

        borrowInfo.getParam().put("returnMethod",returnMethod);
        borrowInfo.getParam().put("moneyUse",moneyUse);
        borrowInfo.getParam().put("status",msgStatus);


        //2.
        /**
         * 下面查询借款人信息
         * 1.根据borrowInfo可以获得user_id，再根据user_id查询借款人borrower
         * 可以使用条件构造器
          */
        QueryWrapper<Borrower> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",borrowInfo.getUserId());
        Borrower borrower = borrowerMapper.selectOne(queryWrapper);//借款人
        //页面要显示的数据都都在borrower对象里面了，但是不是我们要的直接显示方式，都是数字，所以需要使用vo对象
        //数据组装
        BorrowerDetailVO borrowerDetailVO = borrowerService.getBorrowerDetailVOById(borrower.getId());
        //使用map
        Map<String,Object> map = new HashMap<>();
        map.put("borrowInfo",borrowInfo);
        map.put("borrower",borrowerDetailVO);


        return map;
    }




    //借款认证
    @Override
    public void approval(BorrowInfoApprovalVO borrowInfoApprovalVO) {

        //审批之后是借钱成功，需要修改借款状态
        Long borrowId = borrowInfoApprovalVO.getId();//从前端vo对象中获取借款信息id
        BorrowInfo borrowInfo = baseMapper.selectById(borrowId);//根据借款信息id查询借款信息
        borrowInfo.setStatus(borrowInfoApprovalVO.getStatus());//将借款信息状态修改为前端传来的状态
        baseMapper.updateById(borrowInfo);//更新借款信息---1改为2即审批通过

        //判断状态为2，创建标的
        if(borrowInfoApprovalVO.getStatus().intValue() ==BorrowInfoStatusEnum.BORROW_OK.getStatus().intValue()){
            lendService.createLend(borrowInfoApprovalVO,borrowInfo);
        }

    }


}
